package com.czc.qinglong.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.czc.qinglong.domain.EnvironmentDO;
import com.czc.qinglong.domain.RequestParam;
import com.czc.qinglong.service.QingLongService;
import com.czc.qinglong.util.ResultData;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class QingLongServiceImpl implements QingLongService {

    @Override
    public String getUserToken() {
        //构建http客户端
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(180, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .writeTimeout(180, TimeUnit.SECONDS)
                .build();
        //构建请求
        Request request = new Request.Builder()
                .url(RequestParam.url + "/open/auth/token?" + "client_id=" + RequestParam.clientId + "&" + "client_secret=" + RequestParam.clientSecret)
                .get()
                .build();
        //发送请求
        String token = null;
        try {
            Call call = client.newCall(request);
            Response response = call.execute();
            String tokenResponse = response.body().string();
            JSONObject parseObj = JSONUtil.parseObj(tokenResponse);
            token = parseObj.getJSONObject("data").getStr("token");
        } catch (IOException e) {
            log.error("获取token失败，请检查配置文件是否正确", e);
        }
        return "Bearer " + token;
    }

    /*/
    添加环境变量
     */
    @Override
    public ResultData addEnvironment(EnvironmentDO environmentDO) throws IOException {
        String token = getUserToken();
        //构建http客户端
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(180, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .writeTimeout(180, TimeUnit.SECONDS)
                .build();
        //提取有效cookie
        String pattern = "pt_key=([^;]+); pt_pin=([^;]+);";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(environmentDO.getValue());
        if (m.find()) {
            String effectiveData = "pt_key:" + m.group(1) + ";" + "pt_pin:" + m.group(2) + ";";
            environmentDO.setValue(effectiveData);
        } else {
            return ResultData.errorInfo("填入cookies不包含有效值,新增失败");
        }
        //构建body
        List<EnvironmentDO> list = new ArrayList<>();
        list.add(environmentDO);
        JSONArray array = JSONUtil.parseArray(list);
        MediaType parse = MediaType.parse("application/json;charset=UTF-8");
        RequestBody requestBody = RequestBody.create(parse, array.toString());
        //构建请求
        Request request = new Request.Builder()
                .header("Authorization", token)
                .url(RequestParam.url + "/open/envs")
                .post(requestBody)
                .build();
        try {
            Call call = client.newCall(request);
            Response response = call.execute();
            String addResponse = response.body().string();
            JSONObject obj = JSONUtil.parseObj(addResponse);
            if (obj.getStr("code").toString().equals("200")) {
                return ResultData.successInfo("环境变量添加成功");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResultData.errorInfo("添加失败");
    }

    /*/
    定时任务删除环境变量
     */
    @Override
    public void deleteInvialdEnvironment() {
        String token = getUserToken();
        //构建http客户端
        OkHttpClient client = new OkHttpClient().newBuilder()
                .connectTimeout(180, TimeUnit.SECONDS)
                .readTimeout(180, TimeUnit.SECONDS)
                .writeTimeout(180, TimeUnit.SECONDS)
                .build();
        //构建请求
        Request request = new Request.Builder()
                .header("Authorization", token)
                .url(RequestParam.url + "/open/envs")
                .get()
                .build();
        List<String> list = new ArrayList<>();
        try {
            String environmentData = null;
            Call call = client.newCall(request);
            Response response = call.execute();
            environmentData = response.body().string();

            JSONObject parseObj = JSONUtil.parseObj(environmentData);
            for (Object data : parseObj.getJSONArray("data")) {
                Map<String, Object> map = BeanUtil.beanToMap(data);
                if (map.get("status").toString().equals("1")) {
                    list.add(map.get("id").toString());
                }
            }
            if (list.size() != 0) {
                //删除失效的环境变量
                JSONArray array = JSONUtil.parseArray(list);
                MediaType parse = MediaType.parse("application/json;charset=UTF-8");
                RequestBody requestBody = RequestBody.create(parse, array.toString());
                //构建请求
                Request deleteRequest = new Request.Builder()
                        .header("Authorization", token)
                        .url(RequestParam.url + "/open/envs")
                        .delete(requestBody)
                        .build();
                Call deleteCall = client.newCall(deleteRequest);
                //发送请求
                deleteCall.execute();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        log.info("定时任务执行成功,删除环境变量" + list.size() + "条");
    }
}
